package secondweek.two;

import org.junit.Test;
import org.nutz.lang.Files;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.util.Arrays;

/**
 * Created by zhour on 2016/8/11.
 * 分别用大头和小头模式将整数 a=10240写入到文件中（4个字节），
 * 并且再正确读出来，打印到屏幕上，同时截图UltraEdit里的二进制字节序列，做对比说明
 */
public class LittleAndBigEndian {

    /**
     * 1.把小端数据转换成int
     int i = ByteBuffer.wrap(fourBytes).order(ByteOrder.LITTLE_ENDIAN).getInt();

     2.把大端数据转换成int
     int j = ByteBuffer.wrap(fourBytes).order(ByteOrder.BIG_ENDIAN).getInt();

     所有网络协议也都是采用big endian的方式来传输数据的。所以有时我们也会把big endian方式称之为网络字节序
     */
    @Test
    public void test(){
        File file = new File("D:\\aa");
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        int i = 10240;
        ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[4]);
        byteBuffer.asIntBuffer().put(i);

        byteBuffer.rewind();
        byteBuffer.order(ByteOrder.BIG_ENDIAN);
        byteBuffer.asIntBuffer().put(i);
        System.out.println("BIG_ENDIAN:"+Arrays.toString(byteBuffer.array()));

        byteBuffer.rewind();
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
        byteBuffer.asIntBuffer().put(i);
        System.out.println("LITTLE_ENDIAN:"+Arrays.toString(byteBuffer.array()));

        writeToFile(byteBuffer.array(), file);
        byte[] readByteArray = readBytes(file);

        System.out.println("readByteArray from file："+Arrays.toString(readByteArray));
    }

    private void writeToFile(byte[] bytes, File file){
        FileOutputStream outputStream;
        try {
            outputStream = new FileOutputStream(file);
            outputStream.write(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private byte[] readBytes(File file){
        return Files.readBytes(file);
    }
}
